package com.auction.service.impl;

import com.auction.dto.OrderDTO;
import com.auction.dto.OrderPageQueryDTO;
import com.auction.exception.BusinessException;
import com.auction.mapper.*;
import com.auction.pojo.*;
import com.auction.service.OrderService;
import com.auction.vo.OrderVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AuctionMapper auctionMapper;

    @Autowired
    private BidMapper bidMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private SellerInfoMapper sellerInfoMapper;

    /**
     * 创建订单
     * 
     * @param orderDTO
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Long create(OrderDTO orderDTO, Long userId) {
        // 获取拍卖品信息
        Auction auction = auctionMapper.selectById(orderDTO.getAuctionId());

        // 验证拍卖品是否存在
        if (auction == null) {
            throw new BusinessException("拍卖品不存在");
        }

        // 验证拍卖品状态是否已结束
        if (!"FINISHED".equals(auction.getStatus())) {
            throw new BusinessException("拍卖未结束，无法创建订单");
        }

        // 获取最高出价记录
        Bid highestBid = bidMapper.selectHighestBid(orderDTO.getAuctionId());

        // 验证是否有人竞价
        if (highestBid == null) {
            throw new BusinessException("无人竞价，无法创建订单");
        }

        // 验证创建订单的用户是否为最高出价者
        if (!highestBid.getUserId().equals(userId)) {
            throw new BusinessException("您不是最高出价者，无法创建订单");
        }

        // 获取收货地址信息
        AddressBook addressBook = addressBookMapper.getById(orderDTO.getShippingAddressId());

        // 验证收货地址是否存在
        if (addressBook == null) {
            throw new BusinessException("收货地址不存在");
        }

        // 验证收货地址是否属于当前用户
        if (!addressBook.getUserId().equals(userId)) {
            throw new BusinessException("收货地址不属于当前用户");
        }

        // 创建订单
        Order order = new Order();
        order.setNumber(generateOrderNumber());
        order.setAuctionId(orderDTO.getAuctionId());
        order.setBuyerId(userId);
        order.setSellerId(auction.getSellerId());
        order.setOrderAmount(highestBid.getBidPrice());
        order.setOrderStatus(0); // 0-待支付
        order.setShippingAddressId(orderDTO.getShippingAddressId());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        // 插入订单
        orderMapper.insert(order);

        log.info("创建订单成功，订单ID：{}，拍卖品ID：{}", order.getId(), orderDTO.getAuctionId());

        return order.getId();
    }

    /**
     * 获取订单详情
     * 
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        // 获取订单详情
        OrderVO orderVO = orderMapper.selectVOById(id);

        // 验证订单是否存在
        if (orderVO == null) {
            throw new BusinessException("订单不存在");
        }

        return orderVO;
    }

    /**
     * 取消订单
     * 
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public boolean cancel(Long id, Long userId) {
        // 获取订单信息
        Order order = orderMapper.selectById(id);

        // 验证订单是否存在
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 验证订单是否属于当前用户
        if (!order.getSellerId().equals(userId)) {
            throw new BusinessException("订单不属于当前用户");
        }

        // 验证订单状态是否可以取消
        if (order.getOrderStatus() != 0) {
            throw new BusinessException("订单已支付，无法取消");
        }

        // 更新订单状态
        order.setOrderStatus(6); // 6-已取消
        order.setUpdateTime(LocalDateTime.now());

        // 更新订单
        orderMapper.update(order);

        log.info("取消订单成功，订单ID：{}", id);

        return true;
    }

    /**
     * 确认收货
     * 
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public boolean confirm(Long id, Long userId) {
        // 获取订单信息
        Order order = orderMapper.selectById(id);

        // 验证订单是否存在
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 验证订单是否属于当前用户
        if (!order.getBuyerId().equals(userId)) {
            throw new BusinessException("订单不属于当前用户");
        }

        // 验证订单状态是否为已发货
        if (order.getOrderStatus() != 2) {
            throw new BusinessException("订单状态不是已发货");
        }

        // 更新订单状态
        order.setOrderStatus(3); // 3-已完成
        order.setUpdateTime(LocalDateTime.now());

        // 更新订单
        orderMapper.update(order);

        //更新卖家的累计成交数
        Long sellerId = order.getSellerId();
        SellerInfo sellerInfo = sellerInfoMapper.selectByUserId(sellerId);
        sellerInfo.setTotalSales(sellerInfo.getTotalSales() + 1);
        sellerInfoMapper.update(sellerInfo);

        log.info("确认收货成功，订单ID：{}", id);

        return true;
    }

    /**
     * 发货
     * 
     * @param id
     * @param sellerId
     * @param trackingNumber
     * @return
     */
    @Override
    @Transactional
    public boolean ship(Long id, Long sellerId, String trackingNumber) {
        // 获取订单信息
        Order order = orderMapper.selectById(id);

        // 验证订单是否存在
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 验证订单是否属于当前卖家
        if (!order.getSellerId().equals(sellerId)) {
            throw new BusinessException("订单不属于当前卖家");
        }

        // 验证订单状态是否为已支付
        if (order.getOrderStatus() != 1) {
            throw new BusinessException("订单状态不是已支付");
        }

        // 更新订单状态和物流单号
        order.setOrderStatus(2); // 2-待收货
        order.setTrackingNumber(trackingNumber);
        order.setUpdateTime(LocalDateTime.now());

        // 更新订单
        orderMapper.update(order);

        log.info("发货成功，订单ID：{}，物流单号：{}", id, trackingNumber);

        return true;
    }

    /**
     * 分页查询买家订单列表
     * 
     * @param pageNum
     * @param pageSize
     * @param userId
     * @param orderStatus
     * @return
     */
    @Override
    public PageInfo<OrderVO> pageBuyer(int pageNum, int pageSize, Long userId, Integer orderStatus) {
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);

        // 查询买家订单列表
        List<OrderVO> list = orderMapper.selectByBuyerId(userId, orderStatus);

        return new PageInfo<>(list);
    }

    /**
     * 分页查询卖家订单列表
     * 
     * @param pageNum
     * @param pageSize
     * @param sellerId
     * @param orderStatus
     * @return
     */
    @Override
    public PageInfo<OrderVO> pageSeller(int pageNum, int pageSize, Long sellerId, Integer orderStatus) {
        // 分页查询
        PageHelper.startPage(pageNum, pageSize);

        // 查询卖家订单列表
        List<OrderVO> list = orderMapper.selectBySellerId(sellerId, orderStatus);

        return new PageInfo<>(list);
    }

    /**
     * 生成订单号
     * 
     * @return
     */
    private String generateOrderNumber() {
        // 生成唯一订单号，格式：yyyyMMddHHmmss + 随机4位数字
        return LocalDateTime.now().toString().replaceAll("[-:T.]", "").substring(0, 14)
                + String.format("%04d", (int) (Math.random() * 10000));
    }

    /**
     * 支付订单
     * 
     * @param id 订单ID
     * @param userId 用户ID
     * @return 支付结果
     */
    @Override
    @Transactional
    public boolean pay(Long id, Long userId) {
        // 获取订单信息
        Order order = orderMapper.selectById(id);
    
        // 验证订单是否存在
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
    
        // 验证订单是否属于当前用户
        if (!order.getBuyerId().equals(userId)) {
            throw new BusinessException("订单不属于当前用户");
        }
    
        // 验证订单状态是否为待支付
        if (order.getOrderStatus() != 0) {
            throw new BusinessException("订单状态不是待支付");
        }
    
        // 更新订单状态
        order.setOrderStatus(1); // 1-已支付
        order.setPaymentMethod("在线支付");
        order.setPaymentTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
    
        // 更新订单
        orderMapper.update(order);
    
        log.info("支付订单成功，订单ID：{}", id);
    
        return true;
    }

    /**
     * 分页查询订单列表
     * @param orderPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrderPageQueryDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.page(orderPageQueryDTO);

        return new PageResult<>(page.getTotal(), page.getResult());
    }
}